var express = require('express');
var router = express.Router();
let jwt = require("jsonwebtoken");
let userService = require("../service/userServive")
let typeService = require("../service/typeService")
let typeMenuService = require("../service/typeMenuService");
let typeRouterService = require("../service/typeRouterService");


/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('用户操作');
});


// 查看所有用户
router.get("/list", async (req, res, next) => {
  let result = await userService.query({});
  res.json({
    code: 200,
    data: result
  })
})



// 登录
router.post("/login", async (req, res, next) => {
  let { username, userpwd } = req.body;
  let result = await userService.query({ username, userpwd });
  if (result.length) {
    let token = jwt.sign({
      id: result[0]._id,
      username: result[0].username,
      type: result[0].type,
      pid: result[0].pid,
      img:result[0].img
    }, "abc", {
      expiresIn: 3000 * 60
    })

    // 找到类别，菜单和路由
    let type = await typeService.query({ type: result[0].type });
    let menuList = await typeMenuService.query({ typeid: type[0]._id });
    let routerList = await typeRouterService.query({ typeid: type[0]._id });
    let userinfo = { id: result[0]._id, username: result[0].username, type: result[0].type, typename: type[0].name,img:result[0].img }
    res.json({
      code: 200,
      msg: "登录成功",
      token,
      data: {
        routerList,
        menuList
      },
      userinfo
    });

  } else {
    res.json({
      code: 203,
      msg: "用户名和密码不匹配",
    });

  }
});

router.get('/userManageQuery', async function (req, res, next) {
  let { type, pageindex, pageNum,keyValue } = req.query
  let token = req.headers.token;//取出用户信息

  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      let params = { pid: info.id }
      if (type) {
        params.type = type
      }

      // 模糊查询
      if (keyValue) {
        let key = new RegExp(`${keyValue}`)
        let result = await userService.query({ ...params, username: key }, (pageindex - 1) * pageNum, pageNum * 1)
        let total = await userService.count({ ...params, username: key })
        res.json({
          code: 200,
          msg: "查询成功",
          data: result,
          total
        })
        
      } else {
        let result = await userService.query(params, (pageindex - 1) * pageNum, pageNum * 1)
        let total = await userService.count(params)
        res.json({
          code: 200,
          msg: "查询成功",
          data: result,
          total
        })
      }


    } else {
      res.json({
        code: 203,
        msg: "token过期 请重新登录",
      });
    }
  })


});

//老师批量新增学生
//学生名字 密码是默认是123456  类别是2
router.post("/insertmany", (req, res, next) => {
  let { list } = req.body; //post body  get query/params
  let token = req.headers.token;
  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      // 检查是否有重复的用户名
      let usernameList = list.map((item) => item["姓名"]);
      // console.log(usernameList);
      let result2 = await userService.query({
        username: { $in: usernameList },
      });
      // console.log(result2);
      if (result2.length) {
        res.json({
          code: 201,
          msg: "有存在用户名",
          data: result2.map((item) => item.username),
        });
      } else {
        let pid = info.id;
        let userList = list.map((item) => ({
          username: item["姓名"],
          userpwd: "123456",
          type: 2,
          pid,
        }));

        let result = await userService.userInsertMany(userList);
        res.json({
          code: 200,
          data: result,
        });
      }
    } else {
      res.json({
        code: 203,
        msg: "token过期 请重新登录",
      });
    }
  });
});


// 查增删
router.get("/query", async (req, res, next) => {
  let { type, pageindex = 1, pageNum = 5 ,userid,pwd,newpwd } = req.query;
  let token = req.headers.token;//取出用户信息

  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      if(!userid){
        // 列表渲染
        let params = { type }
        let result = '';
        if (info.type == 1) {
          params.pid = info.id
          result = await userService.query({ type: { $in: params.type }, pid: params.pid }, (pageindex - 1) * pageNum, pageNum * 1)
        } else if(info.type == 0){
          result = await userService.query({ type: { $in: params.type }}, (pageindex - 1) * pageNum, pageNum * 1)
        }else{
          let pInfo = await userService.query({_id:info.id})
          result = await userService.query({ type: { $in: params.type } ,pid: pInfo[0].pid}, (pageindex - 1) * pageNum, pageNum * 1)
        }
  
        let total = await userService.count(params)
  
        res.json({
          code: 200,
          msg: "查询成功",
          data: result,
          total
        })
      }else{

        // 用户查询
        let userinfo = await userService.query({_id:userid})
        if(pwd == userinfo[0].userpwd){
          let result = await userService.update({_id:userid},{$set:{userpwd:newpwd}})
          if(result.nModified){
            res.json({
              code: 200,
              msg: "修改成功",
            })
          }else{
            res.json({
              code: 200,
              msg: "修改失败，请重试",
            })
          }
        }else{
          res.json({
            code: 203,
            msg: "原密码输入有误"
          })
        }
      }

    } else {
      res.json({
        code: 203,
        msg: "token过期 请重新登录"
      })
    }

  })

})


router.post("/add", (req, res, next) => {
  let { username, userpwd, type, pid } = req.body; //post body  get query/params
  let token = req.headers.token;
  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      let userIsTrue = await userService.query({ username })
      if (userIsTrue.length) {
        res.json({
          code: 203,
          msg: "用户名已存在"
        });
      } else {
        if (!pid) {
          pid = info.id;
        }
        let result = await userService.add({
          username,
          userpwd,
          type,
          pid
        });

        res.json({
          code: 200,
          msg: "添加成功",
          data: result
        });
      }

    } else {
      res.json({
        code: 203,
        msg: "token过期 重新登录"
      })
    }
  })

})



router.delete("/del", async (req, res, next) => {
  let {
    _id
  } = req.body;
  let result = await userService.del({
    _id
  });
  if (result.deletedCount) {
    res.json({
      code: 200,
      msg: "删除成功"
    })


  } else {
    res.json({
      code: 203,
      msg: "删除失败"
    })
  }

})


// 修改
router.patch('/update', async (req, res, next) => {
  let { _id, username, userpwd, type,img } = req.body
  let params = {  }
  if(username){
    params.username = username
  }
  if(userpwd){
    params.userpwd = userpwd
  }
  if (type) {
    params.type = type
  }
  if(img){
    params.img = img
  }
  let result = await userService.update({ _id }, { $set: params });
  let result2 = await userService.query({ _id })
  if (result.nModified) {
    res.send({
      code: 200,
      msg: "编辑成功",
      data: result,
      userData: result2
    })
  } else {
    res.send({
      code: 203,
      msg: "编辑失败,请重试",
    })
  }

})


module.exports = router;